package com.example.bookkeeping_book.utility;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.example.bookkeeping_book.R;
import com.example.bookkeeping_book.domain.AccountBook;
import com.example.bookkeeping_book.domain.Consumer;
import com.example.bookkeeping_book.utility.MyDialog;
import com.example.bookkeeping_book.utility.MySqlite;
import com.example.bookkeeping_book.utility.Utility;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;


public class MyFragment extends Fragment implements View.OnClickListener {

    private LayoutInflater mLayoutInflater;
    private View view;



    private Context context;


    private ImageView back;
    private TextView chooseExpend;
    private TextView chooseIncome;
    private TextView setAmount;
    private TextView setConsumptionItem;
    private TextView setConsumer;
    private Button[] bs;
    private Button ok;
    private EditText setRemarks;

    private int flag;       //当前选择记入支出还是收入

    private String amount = ""; //金额
    private String[] info;      //消费项目列表
    private int chooseTid = 0;  //选择消费项目

    private ArrayList<Consumer> consumers;  //用户列表
    private String consumer_str[];  //用户姓名列表
    private int chooseCid = 0;  //选择用户列表

    public MyFragment(int  flag, Context context) {
        this.flag = flag;
        this.context = context;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_layout, container, false);
        if (view != null) {
            init();
        }

        mLayoutInflater = getLayoutInflater();

        return view;
    }

    private void init() {
        back = view.findViewById(R.id.iv_back);

        setRemarks = view.findViewById(R.id.edt_setRemarks);

        chooseExpend = view.findViewById(R.id.tv_chooseExpend);
        chooseIncome = view.findViewById(R.id.tv_chooseIncome);
        setAmount = view.findViewById(R.id.tv_setAmount);
        setConsumptionItem = view.findViewById(R.id.tv_setConsumptionItem);
        setConsumer = view.findViewById(R.id.tv_setConsumer);

        Button add = view.findViewById(R.id.btn_add);
        Button minus = view.findViewById(R.id.btn_minus);
        ok = view.findViewById(R.id.btn_ok);
        bs = new Button[]{view.findViewById(R.id.btn_0), view.findViewById(R.id.btn_1), view.findViewById(R.id.btn_2), view.findViewById(R.id.btn_3), view.findViewById(R.id.btn_4), view.findViewById(R.id.btn_5), view.findViewById(R.id.btn_6), view.findViewById(R.id.btn_7), view.findViewById(R.id.btn_8), view.findViewById(R.id.btn_9), view.findViewById(R.id.btn_del), view.findViewById(R.id.btn_point)};
        for (Button a : bs) {
            a.setOnClickListener(this);
        }

        getAllConsumptionItem(R.raw.item1);
        getAllConsumer();

        if(flag == 0) {
            getAllConsumptionItem(R.raw.item2);
            setConsumptionItem.setText(info[0]);
            setAmount.setText("0.00");
            add.setBackground(context.getDrawable(R.drawable.tomato_button));
            add.setTextColor(context.getColor(R.color.white));
            add.setTextSize(30);
            amount = "";
        }else if(flag == 1){
            getAllConsumptionItem(R.raw.item1);
            setConsumptionItem.setText(info[0]);
            setAmount.setText("0.00");
            minus.setBackground(context.getDrawable(R.drawable.tomato_button));
            minus.setTextColor(context.getColor(R.color.white));
            minus.setTextSize(30);
            amount = "";

        }

//        back.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                finish();
//            }
//        });
//
//        chooseExpend.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                chooseExpend.setBackground(getDrawable(R.drawable.font_line));
//                chooseIncome.setBackground(null);
//                getAllConsumptionItem(R.raw.item1);
//                setConsumptionItem.setText(info[0]);
//                setAmount.setText("0.00");
//                amount = "";
//                flag = 1;
//            }
//        });
//
//        chooseIncome.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                chooseExpend.setBackground(null);
//                chooseIncome.setBackground(getDrawable(R.drawable.font_line));
//                getAllConsumptionItem(R.raw.item2);
//                setConsumptionItem.setText(info[0]);
//                setAmount.setText("0.00");
//                amount = "";
//                flag = 0;
//            }
//        });

        ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                double num_amount = Double.parseDouble(setAmount.getText().toString());
                if (flag == 1)
                    num_amount = -num_amount;
                AccountBook accountBook = new AccountBook(consumers.get(chooseCid).getId(), setConsumptionItem.getText().toString(), num_amount, setRemarks.getText().toString());
                Utility.insert(new MySqlite(context), accountBook);
                Toast.makeText(context, "已计入账单" + num_amount + "元", Toast.LENGTH_SHORT).show();
//                context.finish();
//                System.exit(0);
//                overridePendingTransition(0, 0);
                getActivity().finish();
            }
        });

        setConsumptionItem.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                new AlertDialog.Builder(context)
                        .setTitle("请选择")
                        .setSingleChoiceItems(info, chooseTid, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                chooseTid = i;
                            }
                        })
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                setConsumptionItem.setText(info[chooseTid]);
                            }
                        })
                        .show();
            }
        });

        setConsumer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                getAllConsumer();
                new AlertDialog.Builder(context)
                        .setTitle("请选择")
                        .setSingleChoiceItems(consumer_str, chooseCid, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                chooseCid = i;
                            }
                        })
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                setConsumer.setText(consumers.get(chooseCid).getName());
                            }
                        })
                        .setNeutralButton("删除", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                androidx.appcompat.app.AlertDialog dialog;
                                dialog = new androidx.appcompat.app.AlertDialog.Builder(context)
                                        .setTitle("提示")
                                        .setMessage("是否删除")
                                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialogInterface, int i) {
                                                if (Utility.deleteConsumer(new MySqlite(context), consumers.get(chooseCid).getId())) {
                                                    Toast.makeText(context, "已删除该用户", Toast.LENGTH_SHORT).show();
                                                    chooseCid = 0;
                                                } else {
                                                    Toast.makeText(context, "不可以删除当前用户", Toast.LENGTH_SHORT).show();

                                                }
                                            }
                                        })
                                        .setNegativeButton("取消", null)
                                        .create();
                                dialog.show();

                            }
                        })
                        .setNegativeButton("添加", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                MyDialog myDialog = new MyDialog(context);
                                myDialog.setTitle("添加消费用户");
                                myDialog.setAddOnclickListener("添加", new MyDialog.onAddOnclickListener() {
                                    @Override
                                    public void onAddClick() {
                                        if (!myDialog.getEditText().equals(""))
////                    Log.i(editName.getText().toString(), "onClick: ");
                                            Utility.insert(new MySqlite(context), myDialog.getEditText());
                                        myDialog.dismiss();
                                    }
                                });
                                myDialog.show();
                            }
                        })
                        .show();
            }
        });
    }
    private void getAllConsumptionItem(int id) {
        InputStream is = this.getResources().openRawResource(id);
        try {
            List<String> list = Utility.getInfo(is);
            info = list.toArray(new String[list.size()]);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private void getAllConsumer() {
        consumers = Utility.selectAllConsumer(new MySqlite(context));
        consumer_str = new String[consumers.size()];
        for (int i = 0; i < consumers.size(); i++) {
            consumer_str[i] = consumers.get(i).getName();
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_0:
            case R.id.btn_1:
            case R.id.btn_2:
            case R.id.btn_3:
            case R.id.btn_4:
            case R.id.btn_5:
            case R.id.btn_6:
            case R.id.btn_7:
            case R.id.btn_8:
            case R.id.btn_9:
                if (amount.length() >= 10)
                    break;
                if (amount.indexOf(".") > 0 && amount.indexOf(".") + 3 == amount.length())
                    break;
                Button button = view.findViewById(view.getId());
                if (amount.equals("0"))
                    amount = button.getText().toString();
                else
                    amount += button.getText().toString();
                break;
            case R.id.btn_point:
                if (amount.length() >= 10)
                    break;
                if (amount.indexOf(".") < 0)
                    amount += ".";
                if (amount.length() == 0)
                    amount = "0.";
                break;
            case R.id.btn_del:
                amount = amount.substring(0, amount.length() - 1);
                if (amount.length() == 0)
                    amount = "0";
                break;
        }
        setAmount.setText(amount);
    }
}
